/**
 * visit控制器
 *
 * @author sxf
 * @email sxf02615@163.com
 * @date 2025/1/15
 */
package com.sxf.crm.controller;


import com.sxf.crm.dto.VisitDTO;
import com.sxf.crm.dto.VisitRequest;
import com.sxf.crm.dto.VisitStatusUpdateRequest;
import com.sxf.crm.entity.Visit;
import com.sxf.crm.enums.VisitStatus;
import com.sxf.crm.service.UserService;
import com.sxf.crm.service.VisitService;
import com.sxf.crm.util.SecurityUtils;

import jakarta.validation.Valid;

import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import lombok.RequiredArgsConstructor;

import java.util.List;

/**
 * 拜访控制器
 *
 * @author sxf
 * @email sxf02615@163.com
 * @date 2025/6/1
 */
@RestController
@RequestMapping("/api/visits")
@RequiredArgsConstructor
public class VisitController {

    private final VisitService visitService;
    private final UserService userService;

    @PostMapping
    @PreAuthorize("hasAuthority('visit:create')")
    public ResponseEntity<VisitDTO> createVisit(@Valid @RequestBody VisitRequest request) {
        if (request.getVisitStatus() == null) {
            request.setVisitStatus(VisitStatus.PLANNED.name());
        }
        Visit visit = new Visit();
        BeanUtils.copyProperties(request, visit);
        
        // 设置当前登录用户为拜访人
        visit.setUser(userService.getUserById(SecurityUtils.getCurrentUserId()));
                
        Visit createdVisit = visitService.createVisit(visit, request.getCustomerId(), request.getCollaboratorIds());
        return ResponseEntity.ok(visitService.getVisit(createdVisit.getId()));
    }

    @PutMapping("/{id}")
    @PreAuthorize("hasAuthority('visit:edit')")
    public ResponseEntity<VisitDTO> updateVisit(@PathVariable Long id, @Valid @RequestBody VisitRequest request) {
        Visit visit = new Visit();
        BeanUtils.copyProperties(request, visit);
        visit.setId(id);
        
        return ResponseEntity.ok(visitService.updateVisit(visit, request.getCustomerId(), request.getCollaboratorIds()));
    }

    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('visit:delete')")
    public ResponseEntity<Void> deleteVisit(@PathVariable Long id) {
        visitService.deleteVisit(id);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('visit:view')")
    public ResponseEntity<VisitDTO> getVisit(@PathVariable Long id) {
        return ResponseEntity.ok(visitService.getVisit(id));
    }

    @GetMapping("/user/{userId}")
    @PreAuthorize("hasAuthority('visit:list')")
    public ResponseEntity<List<VisitDTO>> getVisitsByUser(@PathVariable Long userId) {
        return ResponseEntity.ok(visitService.getVisitsByUser(userId));
    }

    @GetMapping("/customer/{customerId}")
    @PreAuthorize("hasAuthority('visit:list')")
    public ResponseEntity<List<VisitDTO>> getVisitsByCustomer(@PathVariable Long customerId) {
        return ResponseEntity.ok(visitService.getVisitsByCustomer(customerId));
    }

    @GetMapping
    @PreAuthorize("hasAuthority('visit:list')")
    public ResponseEntity<Page<VisitDTO>> getVisitsByPage(
            @RequestParam(required = false) String title,
            @RequestParam(required = false) String visitType,
            @RequestParam(required = false) String visitStatus,
            @RequestParam(required = false) Long userId,
            @RequestParam(required = false) Long customerId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "createAt") String sort,
            @RequestParam(defaultValue = "desc") String direction) {
        
        Sort.Direction sortDirection = Sort.Direction.fromString(direction.toUpperCase());
        PageRequest pageRequest = PageRequest.of(page, size, Sort.by(sortDirection, sort));
        
        Page<VisitDTO> visits = visitService.getVisitsByPage(
                title, visitType, visitStatus, userId, customerId, pageRequest);
        return ResponseEntity.ok(visits);
    }

    @PutMapping("/{id}/status")
    @PreAuthorize("hasAuthority('visit:edit')")
    public ResponseEntity<VisitDTO> updateVisitStatus(@PathVariable Long id, @Valid @RequestBody VisitStatusUpdateRequest request) {
        return ResponseEntity.ok(visitService.updateVisitStatus(id, request.getVisitStatus()));
    }

} 